package org.nepu.su.controller;

import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.anno.AuthLogin;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.jpa.utils.JpaDataUtil;
import org.nepu.sc.dict.SafeRateDict;
import org.nepu.sc.mx.params.SafeMxParams;
import org.nepu.sc.task.SafeTask;
import org.nepu.sc.task.SafeTaskService;
import org.nepu.sc.task.params.SafeTaskAddParams;
import org.nepu.sc.task.params.SafeTaskQueryParams;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("safe")
@AllArgsConstructor
@Api(tags = "安全评价任务管理")
public class SafeTaskController {
    SafeTaskService taskService;

    @AuthLogin
    @PostMapping("tasks")
    @ApiOperation(value = "任务新建")
    public ResponseDTO<Object> taskCreate(@Validated @RequestBody SafeTaskAddParams params){
        String taskName = params.getTaskName();
        SafeTask task = new SafeTask();
        task.setTaskName(taskName);
        return ResponseDTO.succData(
                taskService.saveOne(task)
        );
    }


    @AuthLogin
    @GetMapping("tasks")
    @ApiOperation(value = "任务列表")
    public ResponseDTO<Object> taskListQuery(SafeTaskQueryParams params){
        Pageable pageable = JpaDataUtil.buildPageable(params);
        Specification<SafeTask> spec = (root, query, cb) -> {
            return cb.like(root.get("taskName"),"%"+params.getSearchKey()+"%");
        };
        if (Validator.isEmpty(params.getSearchKey())){
            return ResponseDTO.succData(
                    taskService.getAll(pageable)
            );
        }else {
            return ResponseDTO.succData(
                    taskService.getAll(pageable,spec)
            );
        }
    }

    @AuthLogin
    @DeleteMapping("tasks/{id}")
    @ApiOperation(value = "任务删除")
    public ResponseDTO<Object> taskDelete(@PathVariable("id") String id){
        taskService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }
}
